﻿using FytApi.MUI;

namespace Digitalmes.ApiService.Swagger;

public static class SwaggerConfig
{
    private static readonly SwaggerVersion[] SwaggerVersions =
    {
        new SwaggerVersion { Version="sys", Title = "系统", Code = "Sys" },
        new SwaggerVersion { Version="mes", Title = "MES", Code = "MES" },
        new SwaggerVersion { Version="scada", Title = "SCADA", Code = "SCADA" },
    };

    public static void AddSwaggerConfiguration(this IServiceCollection services)
    {
        if (services == null) throw new ArgumentNullException(nameof(services));

        services.AddSwaggerGen(s =>
        {
            foreach (var item in SwaggerVersions)
            {
                s.SwaggerDoc(item.Version, new OpenApiInfo
                {
                    Version = item.Version,
                    Title = item.Title,
                });
            }
            s.OrderActionsBy(o => o.RelativePath);

            //Add Xml
            //s.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "FytSoa.Domain.xml"),true);
            var dir = new DirectoryInfo(AppContext.BaseDirectory);
            foreach (var fi in dir.EnumerateFiles("*.xml"))
            {
                var doc = XDocument.Load(fi.FullName);
                s.IncludeXmlComments(() => new XPathDocument(doc.CreateReader()), true);
                //s.SchemaFilter<DescribeEnumMembers>(doc);
            }
            s.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
            {
                Name = "accessToken",
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.ApiKey
            });

            s.AddSecurityRequirement(new OpenApiSecurityRequirement
            {
                {
                    new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference
                        {
                            Type = ReferenceType.SecurityScheme,
                            Id = "Bearer"
                        }
                    },
                    Array.Empty<string>()
                }
            });

        });
    }

    public static void UseSwaggerSetup(this IApplicationBuilder app)
    {
        if (app == null) throw new ArgumentNullException(nameof(app));

        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            foreach (var item in SwaggerVersions)
            {
                c.SwaggerEndpoint($"/swagger/{item.Version}/swagger.json", item.Title + "-" + item.Code);
            }
        });
        app.UseFytApiUI(c =>
        {
            foreach (var item in SwaggerVersions)
            {
                c.SwaggerEndpoint($"/swagger/{item.Version}/swagger.json", item.Title, item.Code);
            }
        });
    }
}
